package com.wn.common.jwt;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yellow Docter
 * @date 2023 -02-27
 * @desc
 */
public class DemoJwT {

    public static void main(String[] args) {

        Map<String,Object> map = new HashMap<>();

        map.put("userId",12);
        map.put("phone","18566230011");

        // 创建密钥对对象
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(
                new ClassPathResource("jwt.jks"),"123456".toCharArray());
        KeyPair keyPair = factory.getKeyPair("jwt");

        // 创建签名器
        JWTSigner jwtSigner = JWTSignerUtil.createSigner("RSA", keyPair);
        //1、创建一个token
        String token = JWTUtil.createToken(map, jwtSigner);

        //xxx.yyy.zzz
        //2、打印token
        System.out.println("token = " + token);

        //3、验证token
        boolean verify = JWTUtil.verify(token, jwtSigner);
        System.out.println("verify = " + verify);

        //4 解析token
        JWT jwt = JWTUtil.parseToken(token);

        Integer userId = (Integer) jwt.getPayload("userId");
        System.out.println("userId = " + userId);

         String phone = (String) jwt.getPayload("phone");
        System.out.println("phone = " + phone);

    }

}
